module.exports = app => {

    const assert = require('http-assert')
    const auth = require('../../middleWares/auth')
    const Role = require('../../models/system/Role')

    /**
     * @description 新增角色
     * */
    app.post('/role', auth('system:role:insert'), async (req, res) => {
        const {roleType} = req.body
        const role = await Role.findOne({roleType})
        assert(!role, 422, '该角色类型已经存在，请不要重复添加。')
        await Role.create(req.body)

        res.send({
            code: 200,
            message: '操作成功'
        })
    })

    /**
     * @description 查询角色列表
     * */
    app.get('/role', auth('system:role:list'), async (req, res) => {
        const {pageNum, pageSize, roleName, status} = req.query
        const regexp = new RegExp(roleName,'i')
        const query = {
            $or: [{roleName: {$regex: regexp}}, {status: {$regex: regexp}}],
        }
        if (status) query.status = status
        const total = await Role
            .find(query)
            .countDocuments()
        const rows = await Role
            .find(query)
            .skip((pageNum - 1) * parseInt(pageSize))
            .limit(parseInt(pageSize))
            .populate('dept')
            .sort({order: 1})

        res.send({
            code: 200,
            message: '操作成功',
            rows,
            total
        })
    })

    /**
     * @description 查询角色详情信息
     * */
    app.get('/role/:roleType', auth('system:role:detail'), async (req, res) => {
        const {roleType} = req.params
        const data = await Role.findOne({roleType})

        res.send({
            code: 200,
            message: '操作成功',
            data
        })
    })

    /**
     * @description 修改角色信息
     * */
    app.put('/role', auth('system:role:update'), async (req, res) => {
        const {roleType} = req.body
        const role = await Role.findOne({roleType})
        assert(role, 422, '编辑失败，请检查参数是否正确。')
        await Role.findOneAndUpdate({roleType}, req.body)

        res.send({
            code: 200,
            message: '操作成功'
        })
    })

    /**
     * @description 修改角色状态
     * */
    app.put('/role/change', auth('system:role:update'), async (req, res) => {
        const {roleType} = req.body
        await Role.findOneAndUpdate({roleType}, req.body)

        res.send({
            code: 200,
            message: '操作成功'
        })
    })

    /**
     * @description 删除角色信息
     * */
    app.delete('/role', auth('system:role:delete'), async (req, res) => {
        const result = await Role.deleteMany({roleType: {$in: req.body}})
        assert(result['deletedCount'], 422, '删除失败，请检查参数是否有效。')

        res.send({
            code: 200,
            message: '操作成功'
        })
    })

}
